<template>
    <div class="avue-contail"
         :class="{'avue--collapse':isCollapse,}">
        <div class="avue-layout"
             :class="{'avue-layout--horizontal':isHorizontal}">
            <div class="avue-sidebar"
                 v-show="validSidebar">
                <!-- 左侧导航栏 -->
                <logo/>
                <sidebar/>
            </div>
            <div class="avue-main">
                <!-- 顶部导航栏 -->
                <top ref="top"/>
                <!-- 顶部标签卡 -->
                <tags/>
                <search class="avue-view"
                        v-show="isSearch"></search>
                <!-- 主体视图层 -->
                <div id="avue-view"
                     v-show="!isSearch"
                     v-if="isRefresh">
                    <DynamicKeepAlive/>
                </div>
                <div class="avue-footer">
                    <p class="copyright">© 2019-2025 xijia-plus</p>
                </div>
            </div>
        </div>
        <!--  <wechat></wechat>-->
    </div>
</template>

<script>
import wechat from './wechat.vue'
import {validatenull} from 'utils/validate'
import {mapGetters} from "vuex";
import tags from "./tags.vue";
import search from "./search.vue";
import logo from "./logo.vue";
import top from "./top/index.vue";
import sidebar from "./sidebar/index.vue";
import {h} from 'vue'
import {ElNotification} from 'element-plus'
import DynamicKeepAlive from './keepAlive.vue';
import router from "./top/top-msg";

export default {
    components: {
        top,
        logo,
        tags,
        search,
        sidebar,
        wechat,
        DynamicKeepAlive
    },
    name: "index",
    provide() {
        return {
            index: this
        };
    },
    computed: {
        ...mapGetters(["isHorizontal", "isRefresh", "isLock", "isCollapse", "isSearch", "menu", "setting",]),
        validSidebar() {
            return !((this.$route.meta || {}).menu == false || (this.$route.query || {}).menu == 'false')
        },
    },
    props: [],
    watch: {
        // 监听 websocket 消息
        '$store.getters.socketMsgs': {
            //处理接收到的消息
            handler: function () {
                let that = this
                // websocket 封装的消息格式
                let receivedMsg = that.$store.getters.socketMsgs.data;
                console.debug("websocket-msg: " + receivedMsg)
                let obj = JSON.parse(receivedMsg);     // 接收到的数据(json)
                // 解析数据
                // let from = obj.from;                   // 来源Id，上下线时为上下线的用户id
                // let username = obj.username;           // 来源用户，上下线时为上下线的用户名
                // let to = obj.to;                       // 目标Id（接收人用户Id,逗号分隔,所有人时为-ALL)）
                let content = obj.content;             // 内容 (text/json 前后端协商)
                // let extras = obj.extras;               // 扩展内容 (text/json 前后端协商)
                // let createTime = obj.createTime;       // 消息时间
                this.sysMsg(content);
                this.loginOut(content);
            }
        }
    },
    created() {
        this.init();
    },
    methods: {
        init() {
            // 获取或更新字典
            this.dict.refreshDict();
            // 初始化 webSocket
            this.$store.dispatch('webSocketInit');
        },
        //打开菜单
        openMenu(item = {}) {
            this.$store.dispatch("GetMenu", item).then(data => {
                //当点击顶部菜单做的事件
                if (!validatenull(item)) {
                    let itemActive = {};
                    let childItemActive = 0;
                    // vue-router路由
                    if (item.path) {
                        itemActive = item;
                    } else {
                        if (this.menu[childItemActive].length == 0) {
                            itemActive = this.menu[childItemActive];
                        } else {
                            itemActive = this.menu[childItemActive].children[childItemActive];
                        }
                    }
                    this.$store.commit('SET_MENU_ID', item);
                    this.$router.push({
                        path: itemActive.path
                    });
                }
            });
        },
        /**
         * 踢下线处理
         * @param content
         */
        loginOut(content) {
            // 具体信息： 此层数据同数据库消息表数据
            if (content != null && content === "loginOut") {
                this.$confirm("你的账号已被踢下线, 如有疑问请联系管理员", "提示", {
                    confirmButtonText: this.$t("submitText"),
                    // cancelButtonText: this.$t("cancelText"),
                    showCancelButton: false,  // 隐藏取消按钮
                    closeOnClickModal: false, // 禁止点击遮罩层关闭
                    closeOnPressEscape: false, // 禁止按ESC关闭
                    showClose: false,        // 隐藏右上角关闭按钮
                    type: "warning",
                    beforeClose: (action, instance, done) => {
                        // 拦截关闭操作，只允许通过确定按钮关闭
                        if (action === 'confirm') {
                            done();  // 允许通过确定按钮关闭
                        }
                    }
                }).then(() => {
                    this.$store.dispatch("LogOut").then(() => {
                        // websocket 在线状态退出
                        this.$store.dispatch('webSocketOut');
                        // 跳转到登录页
                        this.$router.push({path: "/login"});
                    });
                });
            }
        },
        /**
         * 系统消息处理
         */
        sysMsg(content) {
            // 具体信息： 此层数据同数据库消息表数据
            let adminMsgData = null;
            try {
                adminMsgData = JSON.parse(content);
            } catch (e) {
                return;
            }
            // id 为空 表明不是系统信息, 是通过websocket 直发的消息, 不在系统层进行通知
            if (adminMsgData.id == null) {
                return;
            }
            // 具体消息内容
            let msgData = JSON.parse(adminMsgData.content);
            console.debug("websocket-msg-content: " + JSON.stringify(msgData))
            // 右上角弹出消息
            ElNotification({
                title: msgData.title,
                message: h('i', {style: 'color: teal;cursor: pointer;'}, msgData.message),
                duration: 1000 * 10,
                onClick: function () {
                    // 点击弹出层消息, 判断是否需要跳转路由
                    let routePath = msgData.routePath;
                    if (routePath != null && routePath !== "") {
                        console.log("click-to_route:" + routePath);
                        // 获取url上的参数为查询条件
                        let queryStr = routePath.slice(routePath.indexOf('?') + 1);
                        let params = queryStr.split('&').reduce(function (params, item) {
                            let parts = item.split('=');
                            params[decodeURIComponent(parts[0])] = decodeURIComponent(parts[1]);
                            return params;
                        }, {});
                        // 使用 this.$router.push 方法进行路由跳转
                        this.$router.push({
                            path: routePath,
                            query: {...params, time: new Date().getTime()}
                        });
                    }
                }
            })
            // 播放提示音 (如果需要)
            // this.$refs.audio.currentTime = 0;  // 从头开始播放提示音
            // this.$refs.audio.play();           // 播放
            // this.say2( msgData.content);
        }
    }
};
</script>